<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    public $model = Category::class;

    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $input = $request->input();
        $search = ['title' => ''];
        $parent_id = \request('parent_id');
        $list = Category::apply($search, $input);
        $action = $request->input('action');
        if ($action == 'parent') {
            $list = $list->where('parent_id', '=', 0);
        } else {
            if ($parent_id) {
                $list = $list->where('parent_id', $parent_id);
            } else {
                $list = $list->where('parent_id', '!=', 0);
            }
        }
        $list = $list->orderBy("sort", "desc")->orderBy("id", "asc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function all() {
        $list = Category::where('parent_id', 0)->with('child')->paginate(per_page());
        return $this->paginate($list);
    }


    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $cate = Category::find ($id);
            if ($cate->parent_id == 0) {
                Category::where('parent_id', $cate->id)->delete();
            }
            $cate->delete();
        }
        return $this->success([]);
    }

}

